package com.ruoyi.project.stat.paeaReportWorkload.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.WorkloadType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.stat.paeaReportWorkload.domain.StatisticsDateWrapper;
import com.ruoyi.project.stat.paeaReportWorkload.domain.StatisticsWorkload;
import com.ruoyi.project.stat.paeaReportWorkload.domain.StatisticsWorkloadWrapper;
import com.ruoyi.project.stat.paeaReportWorkload.service.ServiceStatisticsWorkload;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.mapper.DeptMapper;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.tool.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.stat.paeaReportWorkload.mapper.PaeaReportWorkloadMapper;
import com.ruoyi.project.stat.paeaReportWorkload.domain.PaeaReportWorkload;
import com.ruoyi.project.stat.paeaReportWorkload.service.IStatisticsWorkloadService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.ui.ModelMap;

/**
 * BPO工作量统计Service业务层处理
 *
 * @author ruoyi
 * @date 2020-04-11
 */
@Service
public class StatisticsWorkloadServiceImpl extends ServiceImpl<PaeaReportWorkloadMapper, PaeaReportWorkload>  implements IStatisticsWorkloadService
{
    @Autowired
    private PaeaReportWorkloadMapper paeaReportWorkloadMapper;
    @Autowired
    private DeptMapper deptMapper;

    /**
     * 查询BPO工作量统计
     *
     * @param id BPO工作量统计ID
     * @return BPO工作量统计
     */
    @Override
    public PaeaReportWorkload selectPaeaReportWorkloadById(String id)
    {
        return paeaReportWorkloadMapper.selectPaeaReportWorkloadById(id);
    }

    /**
     * 查询BPO工作量统计列表
     *
     * @param logWorkload BPO工作量统计
     * @return BPO工作量统计
     */
    @Override
    public List<PaeaReportWorkload> selectPaeaReportWorkloadList(PaeaReportWorkload logWorkload)
    {
        return paeaReportWorkloadMapper.selectPaeaReportWorkloadList(logWorkload);
    }
    /**
     * 删除BPO工作量统计对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePaeaReportWorkloadByIds(String ids)
    {
        return paeaReportWorkloadMapper.deletePaeaReportWorkloadByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除BPO工作量统计信息
     *
     * @param id BPO工作量统计ID
     * @return 结果
     */
    @Override
    public int deletePaeaReportWorkloadById(String id)
    {
        return paeaReportWorkloadMapper.deletePaeaReportWorkloadById(id);
    }

    @Override
    public void init(ModelMap mmap) {
        mmap.put("workloadType", WorkloadType.workloadCodeNameMap);
        List<Dept> depts = deptMapper.selectAllDepts();
        Map deptMap = new HashMap();
        for(Dept dept:depts){
            deptMap.put(dept.getDeptId(),dept.getDeptName());
        }
        mmap.put("deptMap",deptMap);
        mmap.put("defaultOrg",ShiroUtils.getSysUser().getDeptId());
    }

    @Override
    public List<StatisticsWorkloadWrapper> statistics(String beginWorkDate, String endWorkDate, String userCode, String orgCode, String workType,String statType) {
        StatisticsDateWrapper statisticsDateWrapper = StatisticsDateWrapper
                .getStatisticsDateWrapper(beginWorkDate, endWorkDate);
        if(statisticsDateWrapper==null){return new ArrayList<StatisticsWorkloadWrapper>();}
        List<StatisticsWorkload> yearResult = null;
        Map<String, StatisticsWorkload> yearWorkloadMap = new HashMap<String, StatisticsWorkload>();
        Map paramMap = new HashMap();
        if(StringUtils.isEmpty(endWorkDate)){endWorkDate="";}
        boolean statByDate = endWorkDate.compareTo(beginWorkDate) > 0;
        paramMap.put("statByDate",statByDate);
        /*paramMap.put("dateDay",statisticsDateWrapper.parseDate(statisticsDateWrapper.getDateDay()));
        paramMap.put("endDate",statisticsDateWrapper.parseDate(statisticsDateWrapper.getEndDate()));
        paramMap.put("beginMonthDay",statisticsDateWrapper.parseDate(statisticsDateWrapper.getBeginMonthDay()));
        paramMap.put("beginYearDay",statisticsDateWrapper.parseDate(statisticsDateWrapper.getBeginYearDay()));*/
        paramMap.put("dateDay",statisticsDateWrapper.getDateDay());
        paramMap.put("endDate",statisticsDateWrapper.getEndDate());
        paramMap.put("beginMonthDay",statisticsDateWrapper.getBeginMonthDay());
        paramMap.put("beginYearDay",statisticsDateWrapper.getBeginYearDay());
        paramMap.put("userCode",StringUtils.isNotEmpty(userCode)?userCode:"");
        paramMap.put("orgCode", StringUtils.isNotEmpty(orgCode)?orgCode: ShiroUtils.getSysUser().getDeptId());
        if(StringUtils.isNotEmpty(workType)){
            paramMap.put("workType",StringUtils.isNotEmpty(workType)?workType:"");
        } else if (ServiceStatisticsWorkload.STATISTICS_BY_BPO
                .equals(statType)) {
            StringBuilder str = new StringBuilder("");
            str.append("'"+WorkloadType.扫描.getCode()+"',");
            str.append("'"+WorkloadType.人工补录.getCode()+"',");
            str.append("'"+WorkloadType.强制补录.getCode()+"',");
            str.append("'"+WorkloadType.对账单补录.getCode()+"',");
            str.append("'"+WorkloadType.对账单扫描.getCode()+"',");
            str.append("'"+WorkloadType.打包.getCode()+"',");
            str.append("'"+WorkloadType.入箱.getCode()+"'");
            paramMap.put("statTypeBpo",str.toString());
        }
        for (int i = (statByDate ? 0 : 2); i >= 0; i--) {
            if(paramMap.containsKey("index")){
                paramMap.remove("index");
                paramMap.put("index",i);
            }else{
                paramMap.put("index",i);
            }
            List<StatisticsWorkload> statisticsWorkloads = paeaReportWorkloadMapper.statistics(paramMap);
            if (i == 2) {//本年量
                yearResult = (List<StatisticsWorkload>) (List) statisticsWorkloads;
                for (StatisticsWorkload statisticsWorkload : statisticsWorkloads) {
                    yearWorkloadMap.put(statisticsWorkload.formWorkloadKey(), statisticsWorkload);
                }
            } else if (i == 1) {//本月量
                for (StatisticsWorkload statisticsWorkload : statisticsWorkloads) {
                    StatisticsWorkload workload = yearWorkloadMap.get(statisticsWorkload.formWorkloadKey());
                    workload.appendMonthWorkload(statisticsWorkload);
                }
            } else if (i == 0) {//日期量
                if (statByDate) {//按日期区间
                    yearResult = (List<StatisticsWorkload>) (List) statisticsWorkloads;
                    for (StatisticsWorkload statisticsWorkload : statisticsWorkloads) {
                        statisticsWorkload.appendDayWorkload(statisticsWorkload);
                    }
                } else {//单日期
                    for (StatisticsWorkload statisticsWorkload : statisticsWorkloads) {
                        yearWorkloadMap.get(statisticsWorkload.formWorkloadKey())
                                .appendDayWorkload(statisticsWorkload);
                    }
                }
            }
        }
        List<StatisticsWorkloadWrapper> statisticsWorkloadWrappers = null;
        if (ServiceStatisticsWorkload.STATISTICS_BY_BPO.equals(statType)) {
            statisticsWorkloadWrappers = StatisticsWorkloadWrapper
                    .toStatisticsWorkloadWrapperList(yearResult, statType);
        } else if (ServiceStatisticsWorkload.STATISTICS_BY_AUDIT
                .equals(statType)) {
            statisticsWorkloadWrappers = StatisticsWorkloadWrapper
                    .toStatisticsAduitWrapperList(yearResult, statType);
        }
        return statisticsWorkloadWrappers;
    }
    //更新实体
    @Override
    public int updatePaeaReportWorkload(User user, PaeaReportWorkload entity) {
        WorkloadType workloadType = WorkloadType.getWorkTypeByCode(entity.getWorkType());
        PaeaReportWorkload dbLogWorkLoad4User = this.getPaeaReportWorkload(user,entity.getWorkDate(), workloadType,entity.getOrgCode());
        dbLogWorkLoad4User.setBatchNum(entity.getBatchNum());
        dbLogWorkLoad4User.setWorkLoad(entity.getWorkLoad());
        if (null != dbLogWorkLoad4User && StringUtils.isNotEmpty(dbLogWorkLoad4User.getId())) {
            return paeaReportWorkloadMapper.updatePaeaReportWorkload(dbLogWorkLoad4User);
        }else{
            return paeaReportWorkloadMapper.insertPaeaReportWorkload(dbLogWorkLoad4User);
        }
    }
    //扫描补录等添加工作量
    @Override
    public int writePaeaReportWorkload(User userinfo, Date workDate,WorkloadType workloadType, int workload,String orgCode) {
        PaeaReportWorkload logWorkload = this.getPaeaReportWorkload(userinfo, workDate,workloadType,orgCode);
        logWorkload.setWorkLoad(logWorkload.getWorkLoad() + workload);
        logWorkload.setBatchNum(logWorkload.getBatchNum() + 1);
        if (null != logWorkload && StringUtils.isNotEmpty(logWorkload.getId())) {
            return paeaReportWorkloadMapper.updatePaeaReportWorkload(logWorkload);
        }else{
            return paeaReportWorkloadMapper.insertPaeaReportWorkload(logWorkload);
        }
    }
    // 补扫时，只加数量，不加批次量
    @Override
    public int updatePaeaReportWorkloadAdd(User userinfo, Date trDate,WorkloadType workloadType, int workload) {
        PaeaReportWorkload logWorkload = this.getPaeaReportWorkload(userinfo, trDate,workloadType,userinfo.getDeptId());
        if (null != logWorkload && StringUtils.isNotEmpty(logWorkload.getId())) {
            logWorkload.setWorkLoad(logWorkload.getWorkLoad() + workload);
           return paeaReportWorkloadMapper.updatePaeaReportWorkload(logWorkload);
        } else {
            logWorkload = this.createPaeaReportWorkload(userinfo, trDate,workloadType,userinfo.getDeptId(),0, workload);
            return paeaReportWorkloadMapper.insertPaeaReportWorkload(logWorkload);
        }
    }
    /**
     * add by lisc 2012-12-19 删除批次时候减工作量
     * @param userinfo
     * @param workDate
     * @param workloadType
     * @param workload
     */
    @Override
    public int deleteLogWorkload(User userinfo, Date workDate, WorkloadType workloadType, int workload) {
        PaeaReportWorkload logWorkload = this.getPaeaReportWorkload(userinfo, workDate,
                workloadType,userinfo.getDeptId());
        logWorkload.setWorkLoad(logWorkload.getWorkLoad() - workload);
        logWorkload.setBatchNum(logWorkload.getBatchNum() - 1);
        if (logWorkload.getId() == null) {
           return paeaReportWorkloadMapper.insertPaeaReportWorkload(logWorkload);
        }else{
            return paeaReportWorkloadMapper.updatePaeaReportWorkload(logWorkload);
        }
    }

    public PaeaReportWorkload getPaeaReportWorkload(User user, Date workDate, WorkloadType workloadType, String orgCode) {
        QueryWrapper queryWrapper = new QueryWrapper<PaeaReportWorkload>();
        queryWrapper.eq("work_date",DateTimeUtil.getDateFormat(workDate));
        queryWrapper.eq("org_code",orgCode);
        queryWrapper.eq("work_type",workloadType.getCode());
        queryWrapper.eq("user_code",user.getLoginName());
        List<PaeaReportWorkload> logWorkloads = paeaReportWorkloadMapper.selectList(queryWrapper);
        if (logWorkloads.size() == 0) {
            return this.createPaeaReportWorkload(user, workDate,workloadType,orgCode,0, 0);
        }
        PaeaReportWorkload logWorkload = (PaeaReportWorkload) logWorkloads.get(0);
        return logWorkload;
    }
    public PaeaReportWorkload createPaeaReportWorkload(User userinfo, Date workDate,
                                                WorkloadType workloadType, String orgCode, int batchNum, int workload) {
        PaeaReportWorkload logWorkload = new PaeaReportWorkload();
        logWorkload.setUserCode( userinfo.getLoginName());
        logWorkload.setUserName(userinfo.getUserName());
        logWorkload.setOrgCode(StringUtils.isEmpty(orgCode)?userinfo.getDeptId():orgCode);
        String deptName = userinfo.getDept().getDeptName();
        if(StringUtils.isEmpty(deptName)){
            Dept dept = deptMapper.selectDeptById(userinfo.getDeptId());
            deptName = dept!=null?dept.getDeptName():"";
        }
        logWorkload.setOrgName(deptName);
        logWorkload.setWorkDate(DateTimeUtil.getDateFormat(workDate));
        logWorkload.setWorkType(workloadType.getCode());
        //分行号
        //logWorkload.setAuOrgCode(orgCode);
        logWorkload.setWorkLoad(workload);
        logWorkload.setBatchNum(batchNum);
        return logWorkload;
    }
}
